package it.csi.finregio.finreges.client.services;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;

import it.crp.crparch.web.struts.service.CRPStrutsService;
import it.crp.crparch.web.struts.service.WebServiceException;
import it.crp.exception.ServiceException;
import it.crp.logger.PrdLoggerFactory;
import it.csi.finregio.finreges.client.ServiceLocator;
import it.csi.finregio.finreges.dto.NotaScadenza;
import it.csi.finregio.finreges.dto.Scheda;
import it.csi.finregio.finreges.integration.SchedaService;
import it.csi.finregio.finreges.presentation.form.SchedaForm;

public class SalvaNoteScadenzaService implements CRPStrutsService {

	private Logger log = PrdLoggerFactory.getInstance().getLogger("finreges");

	public Object execute(ActionForm form) throws WebServiceException {
		log.info("[SalvaNoteScadenzaService::execute] BEGIN");
		try {
			SchedaForm sf = (SchedaForm) form;
			boolean insert = (sf.getNoteInterne() != null && !sf
					.getNoteInterne().trim().equals(""))
					|| (sf.getDataScadenza() != null && !sf.getDataScadenza()
							.trim().equals(""))
					|| (sf.getTermineScadenza() != null && !sf
							.getTermineScadenza().trim().equals(""));
			if(!insert){
				return sf;
			}
			NotaScadenza ns = new NotaScadenza();
			ns.setIdNota(sf.getIdNota());
			if (sf.getTipoInserimento().equals("1")) {
				ns.setDataScadenza(sf.getDataScadenza());
			}
			if (sf.getTipoInserimento().equals("2")) {
				ns.setTermineScadenza(sf.getTermineScadenza());
			}
			ns.setNotaInterna(sf.getNoteInterne());
			SchedaService ss = new ServiceLocator().getSchedaService();
			Scheda scheda = ss.findSchedaByIdScheda(sf.getIdScheda());
			ns.setScheda(scheda);
			if (ns.getIdNota() == null || ns.getIdNota().trim().equals("")) {
				ns = ss.createNotaScadenza(ns);
				sf.setIdNota(ns.getIdNota());
			} else {
				ns = ss.aggiornaNoteScadenza(ns);
			}
			if(!sf.getStatoScheda().equals(scheda.getStato().getIdStato())){
				scheda.getStato().setIdStato(sf.getStatoScheda());
				ss.aggiornaScheda(scheda);
			}

			return sf;
		} catch (ServiceException e) {
			log.error("[SalvaNoteScadenzaService::execute]  " + e.getMessage(),
					e);
			throw new WebServiceException(e.getMessage());
		} catch (Exception e) {
			log.error("[SalvaNoteScadenzaService::execute]  " + e.getMessage(),
					e);
			throw new WebServiceException(e.getMessage());
		}
	}

}
